import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Upload,
  Radio,
  Input,
  Space,
  Select,
  message
} from 'antd'
import { useRef, useState, useEffect } from 'react'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { observer } from 'mobx-react-lite'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import './index.scss'
import {useStore } from '../../store'
import { http } from '../../utils'
const { Option} = Select
const Publish = () => {
  // 从父组件获取公共数据接口函数-频道
  const { channelStore } = useStore()  
  //导航
  const navigate = useNavigate()

 //使用 useRef 声明一个图片暂存仓库
 const cacheImgList = useRef([])
  //上传图片列表
  const [ fileList, setFileList] = useState([])
  // 点击图片上传
  const onUploadChange = ({fileList}) => {
    // 这里关键位置:需要做数据格式化
    const formatList = fileList.map(file => {
      if (file.response) {// 上传完毕 做数据处理
        return {
          url: file.response.data.url
        }
      }
      // 否则在上传中时，不做处理
      return file
    })
    setFileList(formatList)
    //将图片列表存入仓库
    cacheImgList.current = formatList
  }

  // 切换图片张数类型
  const [imgCount, setImageCount] = useState(1)
  //点击radio选择图片张数
  const radioChange = (e) => {
    // 这里要使用e.target.value做判断
     //这里的判断一句我们采取原始值，不采取经过useState方法修改之后的数据
    //useState修改之后的数据，无法同步采取修改之后的新值
    const rawValue = e.target.value
    setImageCount(rawValue)
    //从仓库里取对应的图片数量，交给我们的fileList渲染图片
    // 无图模式
    if (cacheImgList.current.length === 0) {
      return false
    }
    //单图
    if(rawValue === 1){
      const singleImg = cacheImgList.current ? cacheImgList.current[0] : []
      setFileList([singleImg])
     
    }else if(rawValue === 3){ //多图
      setFileList(cacheImgList.current )
    }
  }

  //提交表单
  const onFinish = async (values) => {
    const { channel_id, content, title, type} = values
    const params = {  //参数
      channel_id,
      content,
      title,
      type,
      cover:{  //图片层级处理
        type:type,
        images: fileList.map(item => item.url)
      }
    }
    // 判断是否存在数据id
    if(articleId){  //存在调用更新接口
      await http.put(`mp/articles/${articleId}?draft= false`, params)
    }else{  //不存在调用发布接口
      await http.post('mp/articles?draft=false', params)
    }
    
    navigate('/article')
    message.success(`${articleId? '更新成功' : '发布成功'}`)
  }

  //编辑功能 文案适配 路由参数id 判断条件
  const [ params ] = useSearchParams()
  const articleId = params.get('id')
  //数据回填 根据id请求数据接口 1.表单回填  2.暂存列表  3.Upload组件fileList
  const form = useRef(null)
  useEffect(() => {
    const onUpdate = async () => {
      const res = await http.get(`/mp/articles/${articleId}`)
      const data = res.data
      //回填 实例方法
      form.current.setFieldsValue({...data, type:data.cover.type})
      //通过setFieldsValue方法回填Upload
      const formatImgList = data.cover.images.map(url => ({ url }))
      setFileList(formatImgList)
      //暂存一份images, (暂存列表和fileList回显列表保持数据结构统一即可)
      cacheImgList.current = formatImgList
    }
    if(articleId){  //必须是编辑状态才能发送编辑接口
      onUpdate()
    }
  }, [articleId]);
  
  return (
    <div className="publish">
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{articleId? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          onFinish={onFinish}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ type: 1, content: '' }}
          ref={form}>
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]} >
            <Input placeholder="请输入文章标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择文章频道' }]}>
            <Select placeholder="请选择文章频道" style={{ width: 400 }}>
              {channelStore.channelList.map(item => <Option key={item.id} value={item.id}>{item.name}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label="封面">
            <Form.Item name="type">
              <Radio.Group onChange={radioChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>
              {imgCount > 0 && (
                <Upload
                  name="image"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList
                  action="http://geek.itheima.net/v1_0/upload"
                  fileList={fileList}
                  onChange={onUploadChange}
                  multiple={imgCount > 1}
                  maxCount={imgCount}
                  >
                  <div style={{ marginTop: 8 }}>
                    <PlusOutlined />
                  </div>
              </Upload>
              )}
          </Form.Item>
          {/* 这里的富文本组件，已经被Form.Item控制，他的输入内容会在onFinished回调中收集 */}
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入文章内容' }]}>
              <ReactQuill theme='snow' />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button size="large" type="primary" htmlType="submit">
                {articleId? '编辑' : '发布'}文章
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default observer(Publish)
